﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using deviceManage.Models;
using deviceManage.vo;
using deviceManage.Filters;


namespace deviceManage.Controllers
{
    /// <summary>
    /// 管理员对所有项目进行管理
    /// </summary>
    [CheckLoginAttribute]
    public class AdminProjectController : Controller
    {
        private readonly DeviceCtx _context;

        public AdminProjectController(DeviceCtx context)
        {
            _context = context;
        }

        //列表主页
        public IActionResult Index()
        {
            return View();
        }

        //ajax 获取分页数据,在建项目
        public AjaxResult List(int page, int limit, String name)
        {     

            AjaxResult r = new AjaxResult();
            IQueryable<Project> query = _context.Project.Where(p => p.Deleted == 0);
            if (!string.IsNullOrWhiteSpace(name))
            {
                query = query.Where(p => p.Name.Contains(name));
            }

            r.Count =query.Count();
            r.Code = 0;
            try
            { 
                r.Data = query.Include(p=>p.Contract).Include(p=>p.Depart)
                .OrderBy(p =>p.State)
                .OrderByDescending(p => p.FinishDate)
                .Skip((page - 1) * limit).Take(limit) 
                .ToList(); 

            }  
            catch(Exception e)
            {
                r.Msg = e.Message;
            }


            return r;
        }

        //项目完成页面
        public IActionResult Finish()
        {
            return View();
        }

       
        


        /// <summary>
        /// 进入创建页面或者编辑页面
        /// </summary>
        public IActionResult Edit(String id)
        {
            //获取设备分类，用于下拉显示
            var contractList = _context.BuyContract.Where(p => p.Deleted == 0).OrderByDescending(p => p.CreateDate).ToList();

            //获取model
            Project project = new Project();
            if (!string.IsNullOrWhiteSpace(id))
            {
                project = _context.Project.Single(p => p.Id == id);
            }
            else //自动生成ID
            {
                project.Id = System.Guid.NewGuid().ToString();
            }

            var departList = _context.Depart.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList(); //部门

            return View(Tuple.Create(contractList, project, departList));
        }


        [HttpPost]
        public AjaxResult Save(Project obj,string deviceTypeId)
        {
            DeviceType type = _context.DeviceType.SingleOrDefault(p => p.Id == deviceTypeId);
            var exist = _context.Project.Any(p=>p.Id == obj.Id);
            if (obj.Id == null || !exist){ //新增
                obj.CreateDate = DateTime.Now;
                obj.Deleted = 0;
                obj.Finish = 0;
                obj.State = 1;
                _context.Add(obj);
                _context.SaveChanges();
                return AjaxResult.GetOK("保存成功");
            }
            else
            {
                Project contract = _context.Project.Single(p => p.Id == obj.Id);
                contract.DevelopUnit = obj.DevelopUnit;
                contract.Participate = obj.Participate;
                contract.UseUnit = obj.UseUnit;
                contract.DepartId = obj.DepartId;
                contract.Name = obj.Name;                
                contract.Amount = obj.Amount;
                contract.StartTime = obj.StartTime;
                this._context.SaveChanges(); //保存
                return AjaxResult.GetOK("保存成功");
            }
        }       
 

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AjaxResult Delete(string id)
        {
            AjaxResult result = new AjaxResult();
            if (id == null) return AjaxResult.GetError("删除失败！");

            result.Code = 1;
            var Project = _context.Project.FirstOrDefault(m => m.Id == id);
            if (Project == null) return AjaxResult.GetError("未找到数据");

            Project.Deleted = 1;
            _context.SaveChanges();
            return AjaxResult.GetOK("删除成功");
        }       

        /// <summary>
        /// 进入完成页面
        /// </summary>
        /// <returns></returns>
        public IActionResult GoFinish(string id)
        {
            Project projct = _context.Project.Single(p => p.Id == id);
            return View(projct);
        }

        /// <summary>
        /// 项目完成
        /// </summary>
        /// <returns></returns>
        public AjaxResult DoFinish(string id,DateTime finishDate)
        {
            Project p = _context.Project.Single(m => m.Id == id);

            if (DateTime.Compare(p.StartTime.Value, finishDate) > 0)
            {
                return AjaxResult.GetError("项目结束时间不能晚于开始时间");
            }

            p.State = 2;
            p.Finish = 1;
            p.FinishDate = finishDate;
            _context.SaveChanges();

            return AjaxResult.GetOK("操作成功！");
        }


        /// <summary>
        /// 进入创建页面或者编辑页面
        /// </summary>
        public IActionResult Detail(String id)
        {
            //获取设备分类，用于下拉显示
            var contractList = _context.BuyContract.Where(p => p.Deleted == 0).OrderByDescending(p => p.CreateDate).ToList();

            //获取model
            Project project = new Project();
            if (!string.IsNullOrWhiteSpace(id))
            {
                project = _context.Project.Single(p => p.Id == id);
            }            

            return View(Tuple.Create(contractList, project));
        }

    }
}
